//
//  BLMeet_DetailController.m
//  Byelone
//
//  Created by 乔小乔 on 2020/12/16.
//

#import "BLMeet_DetailController.h"
#import "BLMeet_Cell_DetailHeader.h"
#import "BLMeet_Cell_DetailTips.h"
#import "BLMeet_Cell_DetailCommon.h"
#import "BLMYTagController.h"
#import "BLInfoInputController.h"
#import "BLInfoAvatarController.h"

#import "BLMeetGiftCell.h"

#import "BLMeetModel.h"
#import "BLMeetFooter.h"
#import "BLOrderModel.h"


static NSString *reuse_BLMeet_Cell_DetailHeader = @"Reuse_BLMeet_Cell_DetailHeader";
static NSString *reuse_BLMeet_Cell_DetailTips = @"Reuse_BLMeet_Cell_DetailTips";
static NSString *reuse_BLMeet_Cell_DetailCommon = @"Reuse_BLMeet_Cell_DetailCommon";
static NSString *reuse_BLMeet_Cell_DetailGift = @"BLMeetGiftCell";

@interface BLMeet_DetailController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property (nonatomic, strong) UITableView *tableViewList;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) NSMutableArray *arrayData;
@property (nonatomic,strong) BLMeet_Cell_DetailTips * cell_tips;

@property (nonatomic, strong) NSArray *bannerArray;

@property (nonatomic,copy) NSArray * tagIdArray;

@property (nonatomic,copy) NSArray * tagNameArray;

@property (nonatomic, strong) UITextView *currentText;
@property (nonatomic, strong) BLInfoDetailInfo *detailInfo;
@property (nonatomic, strong) BLMeetDetailModel *detailAllInfo;
@property (nonatomic, strong) BLMeetFooter *footerView;

@property (nonatomic,strong) BLOrderOtherModel * giftModel;

@property (nonatomic, assign) NSInteger myPage;//礼物列表的
@end

@implementation BLMeet_DetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrayData = [NSMutableArray new];
    self.view.backgroundColor = BL_COLOR_LINEBACKGROUND;
    [self.view addSubview:self.tableViewList];
    [self.view addSubview:self.backBtn];
    [self.arrayData addObjectsFromArray:@[@"个人信息",@"自我标签",@"自我描述",@"家庭背景",@"兴趣爱好",@"爱情观",@"理想中的Ta",@"对未来的憧憬"]];
    if (self.isShouldEdit) {//是自己的主页可以编辑
        [self loadData];
    }else{
        [self.view addSubview:self.footerView];
    }
    self.myPage = 1;
    
    [self loadDetailData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    [self loadDetailData];
}
- (void)loadData{
    [BLHttpTool getHttpRequest:BL_USER_PHOTOS param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
        NSArray * photos = [[obj objectForKey:@"content"] objectForKey:@"list"];
        __block NSMutableArray * tempArray = [NSMutableArray array];
        [photos enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary * dic = [NSDictionary dictionaryWithDictionary:obj];
            NSString * photoUrl = [dic objectForKey:@"photo"];
            [tempArray addObject:photoUrl];
        }];
        self.bannerArray = [tempArray copy];
        
        [self.tableViewList reloadData];
        
        
    } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
        
    }];
}
- (void)loadDetailData{
    if (self.isShouldEdit) {//自己的主页
        self.detailInfo = [BLUserManager shareUser].detailInfo;
        if (self.detailInfo.styleList.count>0) {
            NSMutableArray *idArray = [NSMutableArray new];
            NSMutableArray *nameArray = [NSMutableArray new];
            for (BLInfoStyleItem *item in self.detailInfo.styleList) {
                [idArray addObject:item.styleId];
                [nameArray addObject:item.styleName];
            }
            self.tagIdArray = idArray;
            self.tagNameArray = nameArray;
        }
        [self.tableViewList reloadData];
    }else{//他人的
        [BLHttpTool getHttpRequest:BL_GC_SEARCHDETAIL param:@{@"searchUserId":@(self.searchUserId)} finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
            [self getGift:^(BOOL isNeedGift) {
                [self.arrayData removeAllObjects];
                if (isNeedGift) {
                    [self.arrayData addObjectsFromArray:@[@"个人信息",@"礼物列表",@"自我标签",@"自我描述",@"家庭背景",@"兴趣爱好",@"爱情观",@"理想中的Ta",@"对未来的憧憬"]];
                }else{
                    [self.arrayData addObjectsFromArray:@[@"个人信息",@"自我标签",@"自我描述",@"家庭背景",@"兴趣爱好",@"爱情观",@"理想中的Ta",@"对未来的憧憬"]];
                }
                
                BLMeetDetailModel *info = [BLMeetDetailModel mj_objectWithKeyValues:obj[@"content"]];
                self.detailAllInfo = info;//全局赋值
                self.detailInfo = info.userHomeDetailVo;//详情赋值
                NSArray * photos = info.userHomePhotoVo[@"list"];//banner
                __block NSMutableArray * tempArray = [NSMutableArray array];
                [photos enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSDictionary * dic = [NSDictionary dictionaryWithDictionary:obj];
                    NSString * photoUrl = [dic objectForKey:@"photo"];
                    [tempArray addObject:photoUrl];
                }];
                self.bannerArray = [tempArray copy];
                if (info.userHomeDetailVo.styleList.count>0) {
                    NSMutableArray *idArray = [NSMutableArray new];
                    NSMutableArray *nameArray = [NSMutableArray new];
                    for (BLInfoStyleItem *item in self.detailInfo.styleList) {
                        [idArray addObject:item.styleId];
                        [nameArray addObject:item.styleName];
                    }
                    self.tagIdArray = idArray;
                    self.tagNameArray = nameArray;
                }
                [self.tableViewList reloadData];
                if (self.detailAllInfo.friendShip==1) {
                    self.footerView.btnLike.hidden = YES;
                    self.footerView.btnUnLike.hidden = NO;
                }else{
                    self.footerView.btnLike.hidden = NO;
                    self.footerView.btnUnLike.hidden = YES;
                }
            }];
            
            
        } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
            
        }];
    }
    
}
- (void)getGift:(void(^)(BOOL isNeedGift))over{
    [BLHttpTool getHttpRequest:BL_C_GIFTRECORD param:@{@"searchUserId":@(self.searchUserId),@"pageNo":@(self.myPage),@"pageSize":@(10)} finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
        BLOrderOtherModel *model = [BLOrderOtherModel mj_objectWithKeyValues:obj[@"content"]];
        self.giftModel = model;
        BOOL isNeedGift = NO;
        if (model.count>0) {
            isNeedGift = YES;
        }
        if (over) {
            over(isNeedGift);
        }
    } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
        if (over) {
            over(NO);
        }
    }];
}
- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 修改某些信息
- (void)setDetail:(NSDictionary *)dict{
    
    [BLHttpTool postWithPath:BL_USER_SETDETAIL params:dict successBlock:^(NSDictionary * _Nonnull obj) {
        if (obj) {
            //            修改成功通知刷新单例个人信息
            [[NSNotificationCenter defaultCenter]postNotificationName:Notification_login object:nil];
        }
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - 点击底部
- (void)clickChat{
    
}
- (void)clickLike:(NSInteger)friendShip{
    [BLHttpTool postWithPath:BL_C_SETSHIP params:@{@"friendUserId":@(self.searchUserId),@"friendShip":@(friendShip)} successBlock:^(NSDictionary * _Nonnull obj) {
        if (friendShip==1) {//喜欢成功，变成取消按钮，否则，反之
            self.footerView.btnLike.hidden = YES;
            self.footerView.btnUnLike.hidden = NO;
            self.detailAllInfo.friendShip = 1;
        }else{
            self.footerView.btnLike.hidden = NO;
            self.footerView.btnUnLike.hidden = YES;
            self.detailAllInfo.friendShip = 0;
        }
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = self.arrayData[indexPath.row];
    if ([str isEqualToString:@"个人信息"]) {
        BLMeet_Cell_DetailHeader *cell = [tableView dequeueReusableCellWithIdentifier:reuse_BLMeet_Cell_DetailHeader forIndexPath:indexPath];
        cell.isShouldEdit = self.isShouldEdit;
        [cell reloadWithData:self.bannerArray withData:self.detailAllInfo];
        cell.editBlock = ^(NSInteger index) {
            BLInfoInputController *vc = [[BLInfoInputController alloc]init];
            vc.isEdit = YES;
            [self.navigationController pushViewController:vc animated:YES];
        };
        cell.camaraBlock = ^{
            BLInfoAvatarController *vc = [[BLInfoAvatarController alloc]init];
            vc.isEdit = YES;
            [self.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }else if ([str isEqualToString:@"自我标签"]) {
        BLMeet_Cell_DetailTips *cell = [tableView dequeueReusableCellWithIdentifier:reuse_BLMeet_Cell_DetailTips forIndexPath:indexPath];
        cell.labelTitle.text = str;
        cell.isShouldEdit = self.isShouldEdit;
        [cell reloadWithData:self.tagNameArray];
        cell.editBlock = ^(NSInteger index) {
            NSLog(@"开始编辑自我描述");
            
            BLMYTagController * tagVC = [[BLMYTagController alloc]init];
            if (self.tagIdArray) {
                tagVC.tagIdArray = [NSMutableArray arrayWithArray:self.tagIdArray];
            }
            if (self.tagNameArray) {
                tagVC.tagNameArray = [NSMutableArray arrayWithArray:self.tagNameArray];
            }
            [self.navigationController pushViewController:tagVC animated:YES];
            tagVC.tag = ^(NSArray *idArray, NSArray *nameArray) {
                //                NSIndexPath * index = indexPath;
                BLMeet_Cell_DetailTips * tipsCell =  [self.tableViewList cellForRowAtIndexPath:indexPath];
                [tipsCell reloadWithData:nameArray];
                self.tagIdArray = idArray;
                self.tagNameArray = nameArray;
                NSString *strTag = [idArray componentsJoinedByString:@","];
                [self setDetail:@{@"style":strTag}];
            };
            
        };
        BLWS(weakSelf)
        [cell blockReloadContent:^{
            [weakSelf.tableViewList beginUpdates];
            [weakSelf.tableViewList endUpdates];
        }];
        return cell;
    }else if ([str isEqualToString:@"礼物列表"]) {
        
        BLMeetGiftCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BLMeetGiftCell"];
        cell.giftModel = _giftModel;
        cell.presentGift = ^{
            //赠送
        };
        cell.showInfo = ^(BLOtherItem * _Nonnull itemModel) {
            //点击头像
        };
        return cell;
   
    }else{
        BLMeet_Cell_DetailCommon *cell = [tableView dequeueReusableCellWithIdentifier:reuse_BLMeet_Cell_DetailCommon forIndexPath:indexPath];
        cell.labelTitle.text = str;
        //
        cell.isShouldEdit = self.isShouldEdit;
        
        NSString *strText;
        if ([str isEqualToString:@"自我描述"]) {
            strText = self.detailInfo.selfDesc;
        }else if ([str isEqualToString:@"家庭背景"]) {
            strText = self.detailInfo.familyBg;
        }else if ([str isEqualToString:@"兴趣爱好"]) {
            strText = self.detailInfo.hobby;
        }else if ([str isEqualToString:@"爱情观"]) {
            strText = self.detailInfo.lovePoint;
        }else if ([str isEqualToString:@"理想中的Ta"]) {
            strText = self.detailInfo.idealPartner;
        }else if ([str isEqualToString:@"对未来的憧憬"]) {
            strText = self.detailInfo.future;
        }
        
        [cell reloadWithData:strText];
        BLWS(weakSelf)
        [cell blockReloadContent:^{
            [weakSelf.tableViewList beginUpdates];
            [weakSelf.tableViewList endUpdates];
        }];
        
        __weak __typeof(&*cell)weakCell = cell;
        cell.editBlock = ^(NSString * _Nullable text,BOOL isSave) {
            NSString *key = @"";
            if ([str isEqualToString:@"自我描述"]) {
                key = @"selfDesc";
                self.detailInfo.selfDesc = text;
            }else if ([str isEqualToString:@"家庭背景"]) {
                key = @"familyBg";
                self.detailInfo.familyBg = text;
            }else if ([str isEqualToString:@"兴趣爱好"]) {
                key = @"hobby";
                self.detailInfo.hobby = text;
            }else if ([str isEqualToString:@"爱情观"]) {
                key = @"lovePoint";
                self.detailInfo.lovePoint = text;
            }else if ([str isEqualToString:@"理想中的Ta"]) {
                key = @"idealPartner";
                self.detailInfo.idealPartner = text;
            }else if ([str isEqualToString:@"对未来的憧憬"]) {
                key = @"future";
                self.detailInfo.future = text;
            }
            if (self.currentText!=weakCell.textContent) {
                self.currentText = weakCell.textContent;
            }
            if (isSave) {
                if (![NSString blIsBlankString:key]) {
                    NSDictionary *dict = @{key:text?:@""};
                    [self setDetail:dict];
                }
            }
        };
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *str = self.arrayData[indexPath.row];
    if ([str isEqualToString:@"礼物列表"]) {
        return 169.5;
    }
    return UITableViewAutomaticDimension;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.currentText) {
        [self.currentText resignFirstResponder];
        self.currentText = nil;
    }
}
#pragma  mark - textDelegate
- (void)textViewDidChange:(UITextView *)textView{
    
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    self.currentText = textView;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.currentText) {
        [self.currentText resignFirstResponder];
        self.currentText = nil;
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (self.currentText) {
        [self.currentText resignFirstResponder];
        self.currentText = nil;
    }
}
#pragma mark - get
- (UITableView *)tableViewList{
    if (!_tableViewList) {
        _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, BL_WINDOW_WIDTH, BL_WINDOW_HEIGHT-BL_BOTTOM_MARGIN-(self.isShouldEdit?0:88))];
        [self.view addSubview:_tableViewList];
        _tableViewList.backgroundColor = [UIColor clearColor];
        _tableViewList.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableViewList.delegate = self;
        _tableViewList.dataSource = self;
        //        _tableViewList.tableHeaderView = self.bannerView;
        if (@available(iOS 11.0, *)) {
            _tableViewList.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMeet_Cell_DetailHeader" bundle:nil] forCellReuseIdentifier:reuse_BLMeet_Cell_DetailHeader];
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMeet_Cell_DetailTips" bundle:nil] forCellReuseIdentifier:reuse_BLMeet_Cell_DetailTips];
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMeet_Cell_DetailCommon" bundle:nil] forCellReuseIdentifier:reuse_BLMeet_Cell_DetailCommon];
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMeetGiftCell" bundle:nil] forCellReuseIdentifier:reuse_BLMeet_Cell_DetailGift];
        
    }
    return _tableViewList;
}

- (UIButton *)backBtn{
    if(!_backBtn){
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(16, BL_STATUS_HEIGHT, 44, 44);
        [_backBtn setImage:[UIImage imageNamed:@"bar_back"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _backBtn;
}
- (BLInfoDetailInfo *)detailInfo{
    if (!_detailInfo) {
        _detailInfo = [[BLInfoDetailInfo alloc]init];
    }
    return _detailInfo;
}
- (BLMeetFooter *)footerView{
    if (!_footerView) {
        _footerView = [[[NSBundle mainBundle]loadNibNamed:@"BLMeetFooter" owner:nil options:nil]lastObject];
        _footerView.frame = CGRectMake(0, BL_WINDOW_HEIGHT-BL_BOTTOM_MARGIN-88, BL_WINDOW_WIDTH, 88);
        BLWS(weakSelf)
        _footerView.myBlock = ^(NSInteger index) {
            if (index==0) {
                [weakSelf clickChat];
            }else{
                [weakSelf clickLike:index];
            }
        };
    }
    return _footerView;
}
@end
